<?

/* UserModel model class.
 * This class contains data model implementation code.
 *
 */ 
include_once('lib/fb/facebook.php');
 
class UserModel extends AGModel
{
  // model data
  var $data;

  function __construct($modelName) 
  {
    global $config;
    parent::__construct($modelName);
    $this->fb = new Facebook($config['fb']['api_key'], $config['fb']['secret']);

    #$this->fb->require_login();
    //$this->fb->require_frame();

    if (!isset($_SESSION['user']) || $_SESSION['user']['uid'] == '' || 
      (isset($_REQUEST['fb_sig_user']) && $_REQUEST['fb_sig_user']!=$_SESSION['user']['uid']))
    {
      $this->fb->require_login();
      $this->fb->require_frame();
      $accountInfo = $this->fb->api_client->users_getInfo($this->fb->user, explode(',', 'uid,name,sex,pic_square,is_app_user,has_added_app,birthday,hometown_location,pic_big,first_name,timezone'));
      $_SESSION['user'] = $accountInfo[0];
    }
    else
    {
      $this->fb->api_client->session_key = $_SESSION['fb_sig_session_key'];
    }

    $this->account = &$_SESSION['user'];
    
    $this->loadLocalRecord($this->account['uid']);

    if (sizeof($this->localRecord) == 0 || time()-$this->localRecord['u_lastsync'] > 60*10)
      $this->updateLocalRecord($this->account);
      
    $this->u_key = $this->localRecord['u_key'];
    
    if ($this->localRecord['u_type'] == 'gm')
    {
      $config['menu'][] = array('url' => actionUrl('index', 'gm'), 'caption' => 'GM Tools');
    }
  }

  function loadLocalRecord($fb_uid)
  {
    $this->localRecord = DB_GetDataset('users', $fb_uid, 'u_fb_uid');
  }

  function updateLocalRecord($fbAccountInfo)
  {
    $this->localRecord['u_fb_uid'] = $fbAccountInfo['uid'];
    $this->localRecord['u_fb_name'] = $fbAccountInfo['name'];
    $this->localRecord['u_fb_pic_square'] = $fbAccountInfo['pic_square'];
    $this->localRecord['u_lastsync'] = time();
    $this->localRecord['u_fb_extended'] = serialize($fbAccountInfo);
    $this->localRecord['u_key'] = DB_UpdateDataset('users', $this->localRecord);
  }

}


?>
